package com.cuiweiyou.happypaint.util;

import android.graphics.Bitmap;

import com.cuiweiyou.happypaint.base.BaseApplication;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;

/**
 * Created by lipeng on 2017/12/12.
 */

public class ImageCacheUtil {
    static ImageCacheUtil instance = new ImageCacheUtil();
    String containearPath;

    public static ImageCacheUtil getInstance() {
        return instance;
    }

    /**
     * 设置一个图片缓存目录
     * @param containearPath
     */
    public void init(String containearPath) {
        this.containearPath = containearPath;
        File cachePath = new File(containearPath);
        if (!cachePath.exists()) {
            cachePath.mkdirs();
        }
    }

    /**
     * 根据 目标文件名 保存图片
     * @param bitmap
     * @param fileTargetPath 如果根目录未设置则使用 Application.getContext().getFilesDir().getAbsolutePath() + "/" +
     * @return
     */
    public String save(Bitmap bitmap, String fileTargetPath) {
        if (null != containearPath) {
            fileTargetPath = containearPath + "/" + fileTargetPath;
        }else{
            fileTargetPath = BaseApplication.getContext().getFilesDir().getAbsolutePath() + "/" + fileTargetPath;
        }

        File cachePath = new File(fileTargetPath);
        if (cachePath.exists()) {
            cachePath.delete();
        }

        BufferedOutputStream bos = null;
        try {
            bos = new BufferedOutputStream(new FileOutputStream(fileTargetPath));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);
            bos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != bos) {
                try {
                    bos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        return fileTargetPath;
    }
}

